package com.itheima.redbaby.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.itheima.redbaby.BaseActivity;
import com.itheima.redbaby.R;
import com.itheima.redbaby.bean.Product;
import com.itheima.redbaby.engine.SearchEngine;
import com.itheima.redbaby.factory.DaoAndEngineFactory;
import com.itheima.redbaby.utils.ImageUtil;
import com.itheima.redbaby.utils.PromptManager;

public class SearchResultActivity extends BaseActivity implements OnClickListener{
	private final String TAG = "SearchView";
	private final int PAGE_NUMBER = 10;
	private final String ORDER_SALE_D = "sale_down";
	private final String ORDER_PRICE_U = "price_up";
	private final String ORDER_PRICE_D = "price_down";
	private final String ORDER_COMMENT_D = "comment_down";
	private final String ORDER_SHELVE_D = "shelves_down";
	
	private SearchResultAdapter adapter;
	private int page = 1;
	private String orderby = ORDER_SALE_D;
	private ListView productLv;
	private TextView textRankSale;
	private TextView textRankPrice;
	private TextView textRankGood;
	private TextView textRankTime;
	private String product_name;
	private TextView textTitle;
	private int count;
	private List<Product> list_product = new ArrayList<Product>();
	private LinearLayout linRank;
	private boolean toHide;
	private boolean isSorting;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		init();
		
		Intent preIntent = getIntent();
		product_name = preIntent.getStringExtra("product");
		toHide = true;
		isSorting = false;
		
		getdata();
	}
	
	private void init() {
		setContentView(R.layout.searchlist);
		
		TextView backTv = (TextView) findViewById(R.id.backTv);
		linRank = (LinearLayout) findViewById(R.id.linRank);
		textTitle = (TextView) findViewById(R.id.textTitle);
		textRankSale = (TextView) findViewById(R.id.textRankSale);
		textRankPrice = (TextView) findViewById(R.id.textRankPrice);
		textRankGood = (TextView) findViewById(R.id.textRankGood);
		textRankTime = (TextView) findViewById(R.id.textRankTime);
		productLv = (ListView) findViewById(R.id.productLv);
		
		backTv.setOnClickListener(this);
		textRankSale.setOnClickListener(this);
		textRankPrice.setOnClickListener(this);
		textRankGood.setOnClickListener(this);
		textRankTime.setOnClickListener(this);
		
		adapter = new SearchResultAdapter();
		productLv.setAdapter(adapter);
		// 当滑到底部时该做什么
		productLv.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if(scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
					//如果到头了
					if(view.getLastVisiblePosition() == list_product.size() - 1) {
						//设置页数加1
						page++;
						//重新获取数据
						getdata();
					}
				}
			}
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {}
		});
		productLv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Product product = list_product.get(position);
				Intent intent = new Intent(SearchResultActivity.this, ProductDetailActivity.class);
				intent.putExtra("pId", product.getId());
				startActivity(intent);
			}
		});
	}
	
	/**
	 * 后台获取数据
	 */
	private void getdata() {
		new MyHttpTask() {
			@Override
			protected void onPreExecute() {
				if(toHide)
					linRank.setVisibility(View.INVISIBLE);
//				PromptManager.showProgressDialog(SearchResultActivity.this);
			};
			@Override
			protected Object doInBackground(Void... params) {
				SearchEngine searchEngine = DaoAndEngineFactory.getImpl(SearchEngine.class);
				Map<String, Object> retMap = searchEngine.getProductList(product_name, page, PAGE_NUMBER, orderby);
				return retMap;
			}
			@Override
			@SuppressWarnings("unchecked")
			protected void onPostExecute(Object result) {
//				PromptManager.closeProgressDialog();
				Map<String, Object> retVal = (Map<String, Object>) result;
				count = (Integer) retVal.get("count");
				List<Product> list = (List<Product>) retVal.get("list_product");
				if(isSorting)
					list_product = list;
				else
					list_product.addAll(list);
				SystemClock.sleep(100);
				//如果没有搜索结果则转向没有结果页面
				if(list_product.size() == 0) {
					Intent intent = new Intent(SearchResultActivity.this, SearchNullActivity.class);
					startActivity(intent);
					finish();
				} else {
					linRank.setVisibility(View.VISIBLE);
					textTitle.setText("搜索结果 ( " + count + "条 )");
					adapter.notifyDataSetChanged();
					toHide = false;
					isSorting = false;
				}
			};
		}.executeHttp();
	}

	class SearchResultAdapter extends BaseAdapter {
		@Override
		public int getCount() {
			if(list_product == null || list_product.size() == 0)
				return 0;
			return list_product.size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView == null) {
				convertView = View.inflate(SearchResultActivity.this, R.layout.product_list_items, null);
				SearchHolder holder = new SearchHolder();
				holder.goodsIconIv = (ImageView) convertView.findViewById(R.id.goodsIconIv);
				holder.imgIsNew = (ImageView) convertView.findViewById(R.id.imgIsNew);
				holder.imgIsBargain = (ImageView) convertView.findViewById(R.id.imgIsBargain);
				holder.ProductName = (TextView) convertView.findViewById(R.id.textClothesName);
				holder.ProductPrice = (TextView) convertView.findViewById(R.id.textClothesPrice);
				convertView.findViewById(R.id.prod_comment).setVisibility(View.GONE);
				convertView.setTag(holder);
			}
			SearchHolder holder = (SearchHolder) convertView.getTag();
			Product product = list_product.get(position);
			
			ImageUtil.loadImageFromUrl(holder.goodsIconIv, product.getPic());
			
			holder.ProductName.setText(product.getName());
			Log.i(TAG, product.getName());
			holder.ProductPrice.setText("￥ " + product.getPrice());
			return convertView;
		}

		@Override
		public Object getItem(int position) {
			return position;
		}
		@Override
		public long getItemId(int position) {
			return position;
		}
	}
	
	class SearchHolder {
		ImageView goodsIconIv; //商品图片
		ImageView imgIsNew; //新品
		ImageView imgIsBargain; //特惠
		TextView ProductName; //商品名
		TextView ProductPrice; //会员价格
	}

	@Override
	public void onClick(View v) {
		isSorting = true;
		page = 1;
		switch(v.getId()) {
		case R.id.backTv:
			Intent intent_home = new Intent(this, HomeActivity.class);
			startActivity(intent_home);
			finish();
			break;
		case R.id.textRankSale:
			orderby = this.ORDER_SALE_D;
			getdata();
			changeIndicator(1);
			break;
		case R.id.textRankPrice:
			//如果已经是按价格降序则价格升序，否则价格降序
			if(ORDER_PRICE_D.equals(orderby))
				orderby = ORDER_PRICE_U;
			else
				orderby = this.ORDER_PRICE_D;
			getdata();
			changeIndicator(2);
			break;
		case R.id.textRankGood:
			orderby = this.ORDER_COMMENT_D;
			getdata();
			changeIndicator(3);
			break;
		case R.id.textRankTime:
			orderby = this.ORDER_SHELVE_D;
			getdata();
			changeIndicator(4);
			break;
		}
	}
	
	/**
	 * 设置排序方式控件的背景
	 * @param pos
	 */
	private void changeIndicator(int pos) {
		textRankSale.setBackgroundResource(pos == 1 ? R.drawable.segment_selected_1_bg : R.drawable.segment_normal_1_bg);
		textRankSale.setTextColor(pos == 1 ? Color.WHITE : Color.BLACK);
		textRankPrice.setBackgroundResource(pos == 2 ? R.drawable.segment_selected_2_bg : R.drawable.segment_normal_2_bg);
		textRankPrice.setTextColor(pos == 2 ? Color.WHITE : Color.BLACK);
		textRankGood.setBackgroundResource(pos == 3 ? R.drawable.segment_selected_2_bg : R.drawable.segment_normal_2_bg);
		textRankGood.setTextColor(pos == 3 ? Color.WHITE : Color.BLACK);
		textRankTime.setBackgroundResource(pos == 4 ? R.drawable.segment_selected_3_bg : R.drawable.segment_normal_3_bg);
		textRankTime.setTextColor(pos == 4 ? Color.WHITE : Color.BLACK);
	}
	
}
